﻿using TemplateDemo.Common;
using TemplateDemo.Data;
using TemplateDemo.Model;
using TemplateDemo.Model.user;
using IdentityModel;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json;

namespace TemplateDemo.Service
{
    public class AccountService : IAccountService
    {
        private readonly TemplateDemoDbContext dbContext;
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly ILogger<AccountService> logger;

        public AccountService(TemplateDemoDbContext dbContext, IConfiguration configuration,
          IHttpContextAccessor httpContextAccessor,
          ILogger<AccountService> logger)
        {
            this.dbContext = dbContext;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
            this.logger = logger;
        }
        public async Task<LoginResponse> Login(LoginModel login)
        {
            //1.账号密码是否正确
            var entity_user = await dbContext.Set<User>().
                FirstOrDefaultAsync(c => c.IsDeleted == false && c.UserName == login.UserName);
            if (entity_user == null)
            {
                return new LoginResponse()
                {
                    Message = "用户不存在",
                    IsSuccess = false
                };
            }
            if (entity_user.PassWord != Md5Helper.GetMd5ByString(login.PassWord.Trim() + entity_user.Sale))
            {
                return new LoginResponse()
                {
                    Message = "密码错误",
                    IsSuccess = false
                };
            }
            this.logger.LogError("登入账号密码：" + JsonSerializer.Serialize(login));


            var claims = new List<Claim>
            {
                new Claim("UserType", entity_user.UserType),
               new Claim(JwtClaimTypes.Role,entity_user.UserType),
              new Claim(JwtClaimTypes.Name, entity_user.UserName)
            };
     

                var key = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"]));
                var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(
                    configuration["Authentication:JwtBearer:Issuer"],
                    configuration["Authentication:JwtBearer:Audience"],
                    claims,
                    expires: DateTime.Now.AddHours(1),
                    signingCredentials: credentials
                );
                var token_srt = new JwtSecurityTokenHandler().WriteToken(token);


                return new LoginResponse()
                {
                    Message = "成功",
                    IsSuccess = true,
                    Token = token_srt
                };
            
            
        }
    }
}